var Chat = Vue.component('Chat', {
  template: 
    '<div class="chat">' + 
    '<h2 class="title">在线聊天室</h2>' + 
      '<div class="screen">' + 
        '<div class="content" ref="box">' + 
          '<ul>' + 
            '<li v-for="info in infos">' + 
              '<img class="face" :class="{\'pull-right\': info.user === user}" :src="info.faceImg" alt=""> ' + 
              '<span class="user" :class="{\'pull-right\': info.user === user}">{{info.user}}</span>' + 
             ' <p class="content-info"' + 
                ':class="{\'pull-right\': info.user === user,\'content-my-info\': info.user === user, \'content-else-info\': info.user !== user}">' + 
                '{{info.content}}' + 
              '</p>' + 
            '</li>' + 
          '</ul>' + 
       ' </div>' + 
        '<div class="status">' + 
         ' <div class="status-item count">当前在线：<span v-text="onlines"></span>人</div>' + 
          '<div class="status-item shield" @click="shield = !shield">' + 
           ' <div v-show="!shield" @click="stopListenInfo">' + 
             ' 屏蔽新信息(包括自己)' + 
            '</div>' + 
            '<div v-show="shield" @click="listenInfo">' + 
              '接收新消息' + 
           ' </div>' + 
          '</div>' + 
         ' <div class="status-item clear" @click="clearInfos">清空屏幕</div>' + 
        '</div>' + 
      '</div>' + 
     ' <div class="input-box">' + 
        '<input type="text" class="input" ' + 
          'placeholder="请在这里输入你想要说的话，按ENTER键发送"' + 
          'v-model="info" ' +
         ' @keyup.enter="sendInfo"/>' +
      '</div>' +
    '</div>' +
  '</div>  ',
  data () {
    return {
      infos: [],
      onlines: 0,     //  当前在线人数
      shield: false,  //  屏蔽信息
      info: '',       //  发送新消息
      user: sessionStorage.xuChatUser,
      socket: null
    }
  },
  methods: {
    sendInfo () {
      this.socket.emit('new info', {user: this.user, content: this.info})
      this.info = ''
      this.downScroll()
    },
    clearInfos () {
      this.infos = []
    },
    listenInfo () {
      this.socket.on('new info', function (data) {
        this.$set(this.infos, this.infos.length, Object.assign({},data))
      }.bind(this))
    },
    stopListenInfo () {
      this.socket.removeAllListeners('new info')
    },
    downScroll: function () {
      this.$nextTick(function () {
        this.$refs.box.scrollTop = this.$refs.box.querySelector('ul').offsetHeight - 340 + 10; //默认340高度
      })
    },
  },
  mounted () {

    if (!this.user) {
      this.$router.replace('/login')
    }
    var socket = io.connect('http://localhost:8081')

    socket.on('set infos', function (data) {
      this.infos = data.infos
      this.downScroll()
    }.bind(this))

    socket.on('new user come in', function (data) {
      this.onlines = data.onlines
    }.bind(this))

    socket.emit('new user login')
    socket.emit('get infos')
    this.socket = socket
    this.listenInfo()
  }
})